using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using Husb.Util;
using Husb.Util.Enum;
using CentralOffice.File.Data;
using CentralOffice.File.BusinessActions;
using FileTable = CentralOffice.File.Data.FileDataSet.FileDataTable;
using FileRow = CentralOffice.File.Data.FileDataSet.FileRow;
using CategoryTable = CentralOffice.File.Data.FileCategoryDataSet.FileCategoryDataTable;
using CategoryRow = CentralOffice.File.Data.FileCategoryDataSet.FileCategoryRow;
using FileManager = CentralOffice.File.BusinessActions.Files;


namespace CentralOffice.WebClient.Files
{
    public partial class FileEdit : System.Web.UI.UserControl
    {
        public DropDownList ListBoxControl
        {
            get
            {
                return ddlCategory.Controls[0] as DropDownList;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                SiteUtil.PopulateListBox(ddlSecretLevel, SiteConstants.SecretLevel, false);
                SiteUtil.PopulateListBox(ddlUrgencyPriority, SiteConstants.Priority, false);
                string fileId = HttpContext.Current.Request.QueryString["id"];
                if (String.IsNullOrEmpty(fileId))
                {
                    txtArchivingTime.Text = DateTime.Now.ToString();
                    txtArchivingTime.Enabled = false;
                }
                else
                {
                    SetFields(fileId);
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            Guid fileId = this.Save();
            ClearFields();
            Response.Redirect("FileView.aspx?id=" + fileId.ToString());
            //lblJavaScript.Text = "<script type=\"text/javascript\">window.open('DepartmentAdd.aspx');</script>";
        }

        protected void btnContinue_Click(object sender, EventArgs e)
        {
            this.Save();
            ClearFields();
        }

        private void ClearFields()
        {
            txtName.Text = "";
            txtSubtitle.Text = "";
            txtFileNumber.Text = "";
            txtKeywords.Text = "";
            txtTheme.Text = "";
            txtPublisher.Text = "";
            txtRemark.Text = "";
            txtArchivedBy.Text = "";
        }

        private Guid Save()
        {
            string fileId = HttpContext.Current.Request.QueryString["id"];
            String savePath = SiteUtil.GetDocumentFilePath();
            FileDataSet files = GetFields(fileId, savePath);
            int cnt = FileManager.Update(files);

            SaveFile(savePath);

            return (files.File.Rows[0] as FileRow).Id;
        }

        private void SetFields(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                FileRow file = CentralOffice.File.BusinessActions.Files.GetById(new Guid(id));

                txtName.Text = file.Name;
                //txtNoticeNumber.Text = notice.NoticeNumber;
                //txtQueryNumber.Text = notice.QueryNumber;
                if (!file.IsUrgencyPriorityNull())
                {
                    ddlUrgencyPriority.SelectedValue = EnumUtil.GetInt32(SiteConstants.Priority, CategoryDataSourceType.Xml, file.UrgencyPriority).ToString();
                }
                if (!file.IsSecretLevelNull())
                {
                    ddlSecretLevel.SelectedValue = EnumUtil.GetInt32(SiteConstants.SecretLevel, CategoryDataSourceType.Xml, file.SecretLevel).ToString();
                }

                txtSubtitle.Text = file.IsSubtitleNull() ? "" : file.Subtitle;
                txtFileNumber.Text = file.IsFileNumberNull() ? "" : file.FileNumber;
                txtKeywords.Text = file.IsKeywordsNull() ? "" : file.Keywords;
                txtTheme.Text = file.IsThemeNull() ? "" : file.Theme;

                txtPublisher.Text = file.IsPublisherNull() ? "" : file.Publisher;
                
                //txtFileCategoryId.Text = file.FileCategoryId;
                txtRemark.Text = file.IsRemarkNull() ? "" : file.Remark;
                txtArchivingTime.Text = file.ArchivingTime.ToString();
                txtArchivedBy.Text = file.ArchivedBy;
                txtDepositIn.Text = file.IsDepositInNull() ? "" : file.DepositIn;
            }
        }

        private FileDataSet GetFields(string id, string rootDir)
        {
            FileRow file = null;

            if (String.IsNullOrEmpty(id))
            {
                file = (new FileDataSet()).File.NewFileRow();
                SiteUtil.PopulateCommonField(file, Guid.NewGuid());
                file.ArchivingTime = DateTime.Now;
            }
            else
            {
                // update
                file = CentralOffice.File.BusinessActions.Files.GetById(new Guid(id));
            }
            file.Name = txtName.Text;
            file.FileNumber = txtFileNumber.Text;
            file.QueryNumber = CommonUtil.GetChineseSpell(txtName.Text);
            file.Subtitle = txtSubtitle.Text;
            file.Keywords = txtKeywords.Text;
            file.Theme = txtTheme.Text;

            file.UrgencyPriority = ddlUrgencyPriority.SelectedItem.Text;
            file.Publisher = txtPublisher.Text;
            file.SecretLevel = ddlSecretLevel.SelectedItem.Text;
            file.FileCategoryId = ddlCategory.SelectId.Value;
            file.Remark = txtRemark.Text;
            //file.Attachments = GetAttachments(rootDir);
            if (String.IsNullOrEmpty(id))
            {
                file.Attachments = GetAttachments(rootDir);
            }
            else
            {
                if (file.IsAttachmentsNull() || file.Attachments.Length == 0)
                {
                    file.Attachments = GetAttachments(rootDir);
                }
                else
                {
                    file.Attachments += SiteConstants.CommonSeparatorChar.ToString() + GetAttachments(rootDir);
                }
            }

            file.ArchivedBy = txtArchivedBy.Text.Length == 0 ? CommonUtil.TrimAll(ApplicationContext.ActualUserName) : txtArchivedBy.Text;
            file.DepositIn = txtDepositIn.Text;

            if (String.IsNullOrEmpty(id))
            {
                file.Table.Rows.Add(file);
            }

            string s = SiteUtil.ColumnInRow<string>(file, "DepositIn", "");

            int? i = SiteUtil.ColumnInRow<int?>(file, "Version", null);

            return file.Table.DataSet as FileDataSet;
        }

        private bool SaveFile(string rootDir)
        {
            bool success = false;
            //String savePath = SiteUtil.GetNoticesFilePath(); //Server.MapPath("~/") + "UploadFiles/";
            rootDir = Server.MapPath(rootDir);
            if (FileUpload1.HasFile)
            {
                FileUpload1.SaveAs(rootDir + FileUpload1.FileName);
                if (FileUpload2.HasFile)
                {
                    FileUpload2.SaveAs(rootDir + FileUpload2.FileName);
                }
                success = true;
            }
            else
            {
                //Page.Response.Write("fff");
            }
            return success;
        }

        private string GetAttachments(string rootDir)
        {
            string returnValue = "";
            if (FileUpload1.HasFile)
            {
                returnValue += rootDir + FileUpload1.FileName;
            }

            if (FileUpload2.HasFile)
            {
                returnValue = returnValue.Length > 0 ? returnValue + "|" + rootDir + FileUpload2.FileName : rootDir + FileUpload2.FileName;
            }
            return returnValue;
        }
    }
}